package com.qd.system.util;

import com.cdqidi.constant.ConstantDto;
import com.cdqidi.exception.ApiException;
import com.qd.common.sys.domain.login.LoginUser;
import com.qd.common.sys.util.SecurityUtils;
import com.qd.upload.config.FileConfirmReq;
import com.qd.upload.config.UploadDTO;
import com.qd.upload.constant.FileConfirmDTO;
import com.qd.upload.service.UploadConfirmService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.File;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.List;

/**
 * 文件确认辅助类
 *
 *
 * @author sjk
 */
@Component
@Slf4j
public class FileConfirmUtil {
    private static UploadDTO uploadDto;
    private static UploadConfirmService uploadConfirmService;

    @Autowired
    public FileConfirmUtil(UploadDTO uploadDTO, UploadConfirmService uploadConfirmService) {
        FileConfirmUtil.uploadDto = uploadDTO;
        FileConfirmUtil.uploadConfirmService = uploadConfirmService;
    }


    /**
     * 删除已经确认过的文件
     *
     * @param path 相对路径
     */
    @SneakyThrows
    public static void deleteFileConfirm(String path) {
        String officialPath = uploadDto.getOfficialPath();
        if (StringUtils.hasLength(officialPath)) {
            File file = new File(officialPath + File.separator + path);
            log.info("删除文件,path: {},状态: {}", file.getAbsolutePath(), Files.deleteIfExists(file.toPath()));
            return;
        }
        throw new ApiException("officialPath为空");
    }

    /**
     * 单个文件确认
     *
     * @param id       上传接口返回的ID
     * @param fileType 类型
     * @return 确认信息
     */
    public static FileConfirmDTO singleFileConfirm(String id, String fileType) {
        if (id.startsWith(ConstantDto.HTTP) || id.startsWith(ConstantDto.HTTPS)) {
            return null;
        }
        FileConfirmReq data = buildFileConfirmReq(List.of(id), fileType);
        return uploadConfirmService.singleFileConfirm(data);
    }

    /**
     * 多个文件确认
     *
     * @param ids      上传接口返回的ID列表
     * @param fileType 类型
     * @return 确认信息列表
     */
    public static List<FileConfirmDTO> fileConfirms(List<String> ids, String fileType) {
        FileConfirmReq data = buildFileConfirmReq(ids, fileType);
        return uploadConfirmService.fileConfirms(data);
    }

    /**
     * 图片
     * 拼装下载文件的绝对路径。基于磁盘的下载需要加上前缀路径，后续如果使用S3这里不做操作，直接返回路径
     *
     * @param path 路径
     * @return 绝对路径
     */
    public static String getImageFile(String path) {
        if (StringUtils.hasLength(path)) {
            path = buildPath(uploadDto.getImgDomain(), path);
        } else {
            path = "";
        }
        return path;
    }

    /**
     * 文件
     * 拼装下载文件的绝对路径。基于磁盘的下载需要加上前缀路径，后续如果使用S3这里不做操作，直接返回路径
     *
     * @param path     路径
     * @param fileName 文件名
     * @return 绝对路径
     */
    public static String getFilePath(String path, String fileName) {
        if (StringUtils.hasLength(path)) {
            path = uploadDto.getFileDomain() + "?path=" + URLEncoder.encode(path, StandardCharsets.UTF_8) + "&fileName=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8);
        } else {
            path = "";
        }
        return path;
    }

    /**
     * 拼装参数，id和散列路径
     *
     * @param ids 文件ID集合
     * @return 请求对象
     */
    public static FileConfirmReq buildFileConfirmReq(List<String> ids, String fileType) {
        final LoginUser loginUser = SecurityUtils.getLoginUser();
        String orgId;
        if (StringUtils.hasLength(loginUser.getCurrentOrgId())) {
            orgId = loginUser.getCurrentOrgId();
        } else {
            orgId = "-9999";
        }
        return new FileConfirmReq().setFiles(ids).setInfo(new FileConfirmReq.Info().setAttachmentType(fileType).setTypeKey(orgId + "|" + loginUser.getUserId()));
    }

    /**
     * 裁剪出照片存储的相对路径
     * 传入 http://localhost/sys/sysFile/download/2023/3/2023-03-23/13/20230322填报.jpg
     * 得到 2023/3/2023-03-23/13/20230322填报.jpg
     *
     * @param qrCode 绝对路径
     * @return 相对路径
     */
    public static String getImageRelativePath(String qrCode) {
        if (StringUtils.hasLength(qrCode)) {
            String imgDomain = uploadDto.getImgDomain();
            if (qrCode.startsWith(ConstantDto.HTTP) || qrCode.startsWith(ConstantDto.HTTPS)) {
                qrCode = qrCode.replaceAll(imgDomain, "");
            }
        }
        return qrCode;
    }

    private static String buildPath(String domain, String path) {
//        log.info("domain: {},path: {}", domain,path);
        path = path.replace("\\", "/");
//        log.info("path: {}", domain + path);
        return domain + path;
    }
}
